package com.one.listener;

import com.one.pojo.OneSuper;
import com.one.pojo.OneUser;
import com.one.service.OneSuperService;
import com.one.service.OneUserService;
import com.one.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Description 孵化器拆分定时任务
 * @Author semstouch
 * @Date 2017/5/10
 **/
@Component
public class SuperJobListerner implements ApplicationContextAware,ServletContextAware {
    protected static final Logger logger = LoggerFactory.getLogger(SuperJobListerner.class);
    @Resource
    private OneSuperService oneSuperService;
    @Resource
    private OneUserService oneUserService;

    private ApplicationContext applicationContext;
    private ServletContext servletContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Scheduled(cron = "0 10 00 * * ?")
    public void run() {
        logger.error("进入孵化器拆分时刻!当前时间为" + StringUtils.getStringToday());
        List<OneUser> oneUserList = oneUserService.findAll();
        BigDecimal ratio = new BigDecimal(0.02);
        for(int i= 0;i<oneUserList.size();i++){
            updateSuper(oneUserList.get(i).getUserId(),ratio);
        }

    }

    public void updateSuper(String userId,BigDecimal ratio){
        OneSuper oneSuper = oneSuperService.find(userId);
        if(oneSuper==null){
            return;
        }
        int oldChicksIncome= oneSuper.getChicksIncome();
        int addChicksIncome =oneSuper.getEggNum().multiply(ratio).intValue();
        oneSuper.setChicksIncome(oldChicksIncome+addChicksIncome);
        oneSuperService.update(oneSuper,null);
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}